var http = require('http');
var fs = require('fs');
var url = require('url');

http.createServer(function (req, res) {
  
  var uri = url.parse(req.url, true);
  var path = uri.pathname;
  var stop = false;

  if (path == "/prompt") {
  	if (uri.query && uri.query['magicword']) {
  		var userWord = uri.query['magicword'];
  		
  		if (userWord == "please") {
  			var cookie = "CAuth"+Math.round(Math.random()*999999999999);
			
				res.writeHead(200, {'Content-Type': 'text/html', 
				'Set-Cookie' : "CAuthCookz="+cookie+";expires=Sat, 04-Nov-2011 00:00:00 GMT;path=/;"
				,'P3P': 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'
				});
			  	res.end("<script type=\"text/javascript\">window.close();</script>\n");
			  	return;
		  }
  	}
  	
  	fs.readFile("prompt.html", function (err, data) {
  	if (err)
	    throw err;
	  if (data) {
	  	var txt = data.toString('utf8');
	  	res.writeHead(200, {'Content-Type': 'text/html' });
	  	res.end(txt+'\n');
	  }
  	});
	stop = true;
  }
  
  if (path == "/logout") {
    res.writeHead(200, {'Content-Type': 'text/html', 'Set-Cookie' : "CAuthCookz="+cookie+";expires=Sat, 04-Nov-2000 00:00:00 GMT;path=/;"});
    res.end("\n");
    stop = true;
  }

// stop if no more output is needed.
if (stop) return;

  fs.readFile("printme.js", function (err, data) {
	  if (err)
	    throw err;
	  if (data) {
	    var txt = data.toString('utf8');
	    
	    var cookies = {};
		  req.headers.cookie && req.headers.cookie.split(';').forEach(function( cookie ) {
		    var parts = cookie.split('=');
		    cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
		  });
		 
		var myCAuthResult = "var MyCAuthResult = null;\n";
		
		if (cookies.CAuthCookz) {
			myCAuthResult = "var MyCAuthResult = \""+cookies.CAuthCookz+"\";\n";
		}
		
		res.writeHead(200, {'Content-Type': 'text/javascript' });
	  	res.end(myCAuthResult+txt+'\n');
	  }
	});
  
  
}).listen(8000);
console.log('CAuth Server running at :8000');
